	# Developer: Ryan Smith
	# Copyright 2008 Ryan Smith
		
	# This program is free software: you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation, either version 3 of the License, or
    # (at your option) any later version.

    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    # GNU General Public License for more details.

    # You should have received a copy of the GNU General Public License
    # along with this program.  If not, see <http://www.gnu.org/licenses/>.

#TODO:  Remove clientForms if possilbe
#TODO:  Fix tab problem between name and note field
#TODO:  Add field for opening the given url
#TODO:  Add labels on fields with static text
#TODO:  Add a character counter and display how many posts will be made with the character limit
#TOOD:  Allow to set a character limit
#TODO :  Perhaps support persistent information with pickle?

import wx
import os, sys
import urllib2
import ClientForm
import time

maxSize = 2000

ID_SEND = 100

class MainWindow(wx.Frame):
	def __init__(self, parent, id, title):
		wx.Frame.__init__(self, parent, wx.ID_ANY, title, size = (400,300), style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)

		panel1 = wx.Panel(self, -1) #  txtName txt control
#		panel2 = wx.Panel(self, -1) # txtNote txt control
		panel3 = wx.Panel(self, -1) # buttons
		panel4 = wx.Panel(self, -1) # buttons

#		staticText1 = wx.StaticText(panel1, wx.ID_ANY, "Name: ")
#		staticText2 = wx.StaticText(panel2, wx.ID_ANY, "Note: ")
		
		self.txtName = wx.TextCtrl(panel1, wx.ID_ANY)
		self.txtNote = wx.TextCtrl(panel3, wx.ID_ANY, style = wx.TE_MULTILINE)
		self.statusbar = self.CreateStatusBar()
		
		bSend = wx.Button(panel4, ID_SEND, "Send")
		self.Bind(wx.EVT_BUTTON, self.OnSend, bSend)

		buttonBox = wx.BoxSizer(wx.HORIZONTAL)
		buttonBox.Add(bSend,  0,  wx.ALL | wx.EXPAND, border = 2) # 5
		
		vbox = wx.BoxSizer(wx.VERTICAL)
		hbox1 = wx.BoxSizer(wx.HORIZONTAL)
		hbox2 = wx.BoxSizer(wx.HORIZONTAL)
		hbox3 = wx.BoxSizer(wx.HORIZONTAL)
		hbox4 = wx.BoxSizer(wx.HORIZONTAL)

#		hbox1.Add(staticText1, 2, wx.EXPAND)
		hbox1.Add(self.txtName, 18, wx.EXPAND)
#		hbox2.Add(staticText1, 2, wx.EXPAND)
		hbox3.Add(self.txtNote, 9, wx.EXPAND)
		hbox4.Add(buttonBox, 1,  wx.ALIGN_RIGHT | wx.EXPAND)
		
		vbox.Add(panel1, 1, wx.EXPAND)
#		vbox.Add(panel2, 1, wx.EXPAND)
		vbox.Add(panel3, 8, wx.EXPAND)
		vbox.Add(panel4, 1, wx.EXPAND)

		panel1.SetSizer(hbox1)
#		panel2.SetSizer(hbox2)
		panel3.SetSizer(hbox3)
		panel4.SetSizer(hbox4)

		self.SetSizer(vbox) # from panel
		
		self.Show(True)
	def OnSend(self, event): # Save a file 
		""" Post chunks to web form """
		numString = self.txtNote.GetValue()
		numString = numString.split()  # splits the contents based on words

		chunks = []  # list of chunks, each chuck has len(chunk) < maxSize
		tempChunk = ''  # temporary chunk to concatenate from numString
		chunkLength = 0 # counter to keep track of the len(chunk)
		index = 0		# index in numString to catch all the words of numString

		while index < len(numString):  # check if chunkLength is too big and make sure there isn't an index error
			if (len(tempChunk) + len(numString[index])) >= maxSize or (len(tempChunk) >= maxSize):  # is tempChunk + the next word too much
				chunks.append(tempChunk) # attach the completed chunk to chunks
				tempChunk = ''  # get ready for the next pass
				chunkLength = 0 # get ready for the next pass
			chunkLength += len(numString[index]) + 1 # lenght of the word + 1 for space after the word
			tempChunk += str(numString[index]) + ' ' # word + one space
			index += 1 # move the index over one
		chunks.append(tempChunk) # one final chunk since this was checking with an if statement and not putting the last chunk in chunks

		chunks.reverse() # reverse the order for posting
		
		######### if postThisMessage == False:   # used for printing to the console
		# whichChunk = len(chunks)
		# for chunk in chunks:       # print all the chunks one at a time
			# print self.txtName.GetValue() + " (%s/%s)" % (whichChunk, len(chunks))
			# print "Chunk:  %s\t%s" % (len(chunk), chunk)
			# whichChunk -= 1		url = 'http://www.paveldoichev.com/default.aspx' # url for the site
		
		t0 = time.localtime(time.time())
		request = urllib2.Request(url)   # url valid ?
		response = urllib2.urlopen(request) # open the url ?
		forms = ClientForm.ParseResponse(response, backwards_compat=False) # parse the site, turn off backward-compat mode to supress depreciation-warning
		response.close() # close connection ?

		# print forms on this page
		# for form in forms: 
			# print "***************************"
			# print form
		whichChunk = len(chunks)
		for chunk in chunks:  # print each chunk
			form = forms[0]
			form["txtName"]  = self.txtName.GetValue() + " (%s/%s)" % (whichChunk, len(chunks))   # txtName - first form
			form["txtNote"] = chunk  # body of the post
			whichChunk -= 1
			fp = urllib2.urlopen(form.click())
			fp.close()
		
		t = time.localtime(time.time())
		self.SetStatusText("Sent " + str(whichChunk + 1) + "/" + str(len(chunks)) + " Start: " + time.strftime("%I:%M:%S %p", t0) + " End: " + time.strftime("%I:%M:%S %p", t))  # fix this
		self.txtNote.Clear()

if __name__ == "__main__":
	app = wx.App(0)
	frame = MainWindow(None, -1, "Post to Form")
	app.MainLoop()
